package cn.zmall.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.zmall.common.exception.ZmallException;
import cn.zmall.common.pojo.IpInfo;
import cn.zmall.common.pojo.IpWeatherResult;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author BinBini
 * @Date 2020/12/14 16:43
 * @Version 1.0
 */
public class IPInfoUtil {
    private static final Logger log = LoggerFactory.getLogger(IPInfoUtil.class);

    private final static String APPKEY = "2f6ee0b13aa60";

    /**
     * Mob全国天气预报接口
     */
    private final static String GET_WEATHER = "http://apicloud.mob.com/v1/weather/ip?key="+ APPKEY +"&ip=";

    /**
     * 获取客户端IP地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarder-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if(ip.equals("127.0.0.1")) {
                // 根据网卡取得本机配置IP
                InetAddress inetAddress = null;
                try{
                    inetAddress = InetAddress.getLocalHost();
                }catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = inetAddress.getHostAddress();
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP，多个IP按照','分割
        if(ip != null && ip.length() > 15) {
            if(ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    public static String getIpAddress(String ip) {
        String result = "未知";
        String url = "http://ip.ws.126.net/ipquery?ip=" + ip;
        try{
            result = HttpUtil.sendGet(url);
            if(!StrUtil.hasBlank(result)){
                String substring = result.substring(result.indexOf("{"), result.indexOf("}") + 1);
                JSONObject jsonObject = JSONUtil.parseObj(substring);
                String province = jsonObject.getStr("province");
                String city = jsonObject.getStr("city");
                return province + " " + city;
            }
        }catch (Exception e) {
            throw new ZmallException("获取城市失败");
        }
        return null;
    }

    /**
     * 获取IP返回地理天气信息
     * @param ip
     * @return
     */
    public static String getIpInfo(String ip) {
        if(ip != null) {
            String url = GET_WEATHER + ip;
            String result = HttpUtil.sendGet(url);
            return result;
        }
        return null;
    }

    /**
     * 获取IP返回地理信息
     * @param ip
     * @return
     */
    public static String getIpCity(String ip) {
        if(ip != null) {
            String result = "未知";
            try{
                String url = GET_WEATHER + ip;
                String json = HttpUtil.sendGet(url);
                IpWeatherResult weather = new Gson().fromJson(json, IpWeatherResult.class);
                result = weather.getResult().get(0).getCity()+" "+weather.getResult().get(0).getDistrct();
            }catch (Exception e) {
                throw new ZmallException("获取城市失败");
            }
            return result;
        }
        return null;
    }

    /**
     * 获取IP返回地理信息
     * @param ip
     * @return
     */
    public static String getIpCityByGet(String ip) {
        if(ip != null) {
            String url = GET_WEATHER + ip;
            String json = HttpUtil.sendGet(url);
            String result = "未知";
            try{
                IpWeatherResult weather = new Gson().fromJson(json, IpWeatherResult.class);
                result = weather.getResult().get(0).getCity()+" "+weather.getResult().get(0).getDistrct();
            }catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
        return null;
    }

    public static void getInfo(HttpServletRequest request, String p) {
        try{
            IpInfo info = new IpInfo();
            info.setUrl(request.getRequestURI().toString());
            info.setP(p);
            String result = HttpRequest.post("https://api.bmob.cn/1/classes/url")
                    .header("X-Bmob-Application-Id", "46970b236e5feb2d9c843dce2b97f587")
                    .header("X-Bmob-REST-API-Key", "171674600ca49e62e0c7a2eafde7d0a4")
                    .header("Content-Type", "application/json")
                    .body(new Gson().toJson(info, IpInfo.class))
                    .execute().body();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
